{% extends "base.html" %}

{% block content %}
<div class="login-container">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6 col-xl-5">
                <div class="card login-card shadow-lg">
                    <div class="card-header text-center bg-success text-white">
                        <h4 class="mb-0">
                            <i class="bi bi-person-plus me-2"></i>用户注册
                        </h4>
                    </div>
                    <div class="card-body p-4">
                <form id="registerForm" method="POST">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名</label>
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="bi bi-person"></i>
                            </span>
                            <input type="text" class="form-control" id="username" name="username" 
                                   placeholder="3-20位字母、数字、下划线" required>
                        </div>
                        <div class="form-text" id="usernameHelp"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="real_name" class="form-label">真实姓名</label>
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="bi bi-person-badge"></i>
                            </span>
                            <input type="text" class="form-control" id="real_name" name="real_name" 
                                   placeholder="请输入真实姓名" required>
                        </div>
                        <div class="form-text" id="realNameHelp"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="class_name" class="form-label">班级</label>
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="bi bi-people"></i>
                            </span>
                            <select class="form-select" id="class_name" name="class_name" required>
                                <option value="">请选择班级</option>
                                {% for class_option in class_options %}
                                <option value="{{ class_option.id }}">{{ class_option.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="form-text" id="class_nameHelp"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="password" class="form-label">密码</label>
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="bi bi-lock"></i>
                            </span>
                            <input type="password" class="form-control" id="password" name="password" 
                                   placeholder="至少6位字符" required>
                            <button class="btn btn-outline-secondary" type="button" id="togglePassword">
                                <i class="bi bi-eye"></i>
                            </button>
                        </div>
                        <div class="form-text" id="passwordHelp"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="password2" class="form-label">确认密码</label>
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="bi bi-lock-fill"></i>
                            </span>
                            <input type="password" class="form-control" id="password2" name="password2" 
                                   placeholder="请再次输入密码" required>
                            <button class="btn btn-outline-secondary" type="button" id="togglePassword2">
                                <i class="bi bi-eye"></i>
                            </button>
                        </div>
                        <div class="form-text" id="password2Help"></div>
                    </div>
                    
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="agree" required>
                        <label class="form-check-label" for="agree">
                            我同意遵守系统使用规范
                        </label>
                    </div>
                    
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary" id="registerBtn" disabled>
                            <span class="loading spinner-border spinner-border-sm me-2" role="status"></span>
                            注册账号
                        </button>
                    </div>
                </form>
                    </div>
                    <div class="card-footer text-center bg-light">
                        <p class="mb-0">
                            已有账号？ 
                            <a href="{{ url_for('auth.login') }}" class="text-decoration-none">立即登录</a>
                        </p>
                    </div>
                </div>
                
                <!-- 注册须知 -->
                <div class="card mt-4 login-card">
                    <div class="card-header bg-warning text-dark">
                        <h6 class="mb-0">
                            <i class="bi bi-exclamation-triangle me-2"></i>注册须知
                        </h6>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled mb-0">
                            <li><i class="bi bi-dot text-primary"></i>用户名一旦注册不可修改</li>
                            <li><i class="bi bi-dot text-primary"></i>请使用真实邮箱地址注册</li>
                            <li><i class="bi bi-dot text-primary"></i>请妥善保管账号密码</li>
                            <li><i class="bi bi-dot text-primary"></i>禁止发送垃圾邮件或不当内容</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const registerForm = document.getElementById('registerForm');
    const registerBtn = document.getElementById('registerBtn');
    const togglePassword = document.getElementById('togglePassword');
    const togglePassword2 = document.getElementById('togglePassword2');
    const passwordInput = document.getElementById('password');
    const password2Input = document.getElementById('password2');
    const usernameInput = document.getElementById('username');
    const realNameInput = document.getElementById('real_name');
    const classNameSelect = document.getElementById('class_name');
    const agreeCheckbox = document.getElementById('agree');
    
    // 验证状态
    const validation = {
        username: false,
        password: false,
        password2: false,
        real_name: false,
        class_name: false,
        agree: false
    };
    
    // 密码显示/隐藏切换
    function setupPasswordToggle(toggleBtn, passwordField) {
        toggleBtn.addEventListener('click', function() {
            const type = passwordField.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordField.setAttribute('type', type);
            
            const icon = this.querySelector('i');
            icon.className = type === 'password' ? 'bi bi-eye' : 'bi bi-eye-slash';
        });
    }
    
    setupPasswordToggle(togglePassword, passwordInput);
    setupPasswordToggle(togglePassword2, password2Input);
    
    // 更新按钮状态
    function updateButtonState() {
        const allValid = Object.values(validation).every(v => v);
        registerBtn.disabled = !allValid;
    }
    
    // 显示验证消息
    function showValidationMessage(fieldId, message, isValid) {
        const helpElement = document.getElementById(fieldId + 'Help');
        const inputElement = document.getElementById(fieldId);
        
        if (message) {
            helpElement.textContent = message;
            helpElement.className = `form-text ${isValid ? 'text-success' : 'text-danger'}`;
            inputElement.className = `form-control ${isValid ? 'is-valid' : 'is-invalid'}`;
        } else {
            helpElement.textContent = '';
            inputElement.className = 'form-control';
        }
    }
    
    // 用户名验证
    let usernameTimeout;
    usernameInput.addEventListener('input', function() {
        const username = this.value.trim();
        
        clearTimeout(usernameTimeout);
        
        if (!username) {
            validation.username = false;
            showValidationMessage('username', '', false);
            updateButtonState();
            return;
        }
        
        // 格式验证
        const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/;
        if (!usernameRegex.test(username)) {
            validation.username = false;
            showValidationMessage('username', '用户名只能包含字母、数字、下划线，长度3-20位', false);
            updateButtonState();
            return;
        }
        
        // 延迟检查可用性
        usernameTimeout = setTimeout(async () => {
            try {
                const response = await fetch(`/auth/check_username?username=${encodeURIComponent(username)}`);
                const data = await response.json();
                
                validation.username = data.available;
                showValidationMessage('username', data.message, data.available);
                updateButtonState();
            } catch (error) {
                validation.username = false;
                showValidationMessage('username', '检查用户名失败', false);
                updateButtonState();
            }
        }, 500);
    });
    
    // 密码验证
    passwordInput.addEventListener('input', function() {
        const password = this.value;
        
        if (!password) {
            validation.password = false;
            showValidationMessage('password', '', false);
        } else if (password.length < 6) {
            validation.password = false;
            showValidationMessage('password', '密码长度至少6位', false);
        } else {
            validation.password = true;
            showValidationMessage('password', '密码强度良好', true);
        }
        
        // 重新验证确认密码
        if (password2Input.value) {
            password2Input.dispatchEvent(new Event('input'));
        }
        
        updateButtonState();
    });
    
    // 确认密码验证
    password2Input.addEventListener('input', function() {
        const password = passwordInput.value;
        const password2 = this.value;
        
        if (!password2) {
            validation.password2 = false;
            showValidationMessage('password2', '', false);
        } else if (password !== password2) {
            validation.password2 = false;
            showValidationMessage('password2', '两次输入的密码不一致', false);
        } else {
            validation.password2 = true;
            showValidationMessage('password2', '密码确认正确', true);
        }
        
        updateButtonState();
    });
    
    // 同意条款验证
    agreeCheckbox.addEventListener('change', function() {
        validation.agree = this.checked;
        updateButtonState();
    });
    
    // 真实姓名验证
    realNameInput.addEventListener('input', function() {
        const realName = this.value.trim();
        
        if (!realName) {
            validation.real_name = false;
            showValidationMessage('realName', '', false);
        } else if (realName.length < 2 || realName.length > 20) {
            validation.real_name = false;
            showValidationMessage('realName', '真实姓名长度应在2-20个字符之间', false);
        } else {
            validation.real_name = true;
            showValidationMessage('realName', '姓名格式正确', true);
        }
        
        updateButtonState();
    });
    
    // 班级选择验证
    classNameSelect.addEventListener('change', function() {
        const className = this.value;
        
        if (!className) {
            validation.class_name = false;
            showValidationMessage('class_name', '请选择班级', false);
        } else {
            const classId = parseInt(className);
            if (isNaN(classId) || classId < 0 || classId > 10) {
                validation.class_name = false;
                showValidationMessage('class_name', '请选择有效的班级', false);
            } else {
                validation.class_name = true;
                showValidationMessage('class_name', '班级选择正确', true);
            }
        }
        
        updateButtonState();
    });
    
    // 表单提交处理
    registerForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const data = {
            username: formData.get('username').trim(),
            password: formData.get('password'),
            password2: formData.get('password2'),
            real_name: formData.get('real_name').trim(),
            class_id: formData.get('class_name')
        };
        
        // 最终验证
        if (!Object.values(validation).every(v => v)) {
            showAlert('请完善所有必填信息', 'warning');
            return;
        }
        
        // 显示加载状态
        showLoading(registerBtn, true);
        registerBtn.disabled = true;
        
        try {
            const response = await apiRequest('/auth/register', {
                method: 'POST',
                body: JSON.stringify(data)
            });
            
            if (response.success) {
                showAlert(response.message, 'success');
                
                // 延迟跳转到登录页面
                setTimeout(() => {
                    window.location.href = response.redirect || '/auth/login';
                }, 2000);
            }
        } catch (error) {
            showAlert(error.message, 'danger');
            registerBtn.disabled = false;
        } finally {
            showLoading(registerBtn, false);
        }
    });
});
</script>
{% endblock %}